package com.tgit.sso.paltform.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * ClassName: RedisConfig
 * date: 2019/11/25 10:49
 * Description: redis集群或单机，暂时未用到
 * @author fanzj@tgit.com
 * @since JDK 1.8
 */
//@Configuration
public class RedisConfig {
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMaxTotal(20);
        jedisPoolConfig.setMaxWaitMillis(20000);
        return jedisPoolConfig;
    }

    //集群bean
    @Bean
    public RedisClusterConfiguration redisConfiguration() {
        int size = ConfigInfo.REDIS_CLUSTER.size();
        if(size==1){
            return null;
        }
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(ConfigInfo.REDIS_CLUSTER);
        redisClusterConfiguration.setMaxRedirects(size / 2);
        return redisClusterConfiguration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration,JedisPoolConfig jedisPoolConfig) {
        if(redisClusterConfiguration!=null){
            JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisConfiguration(), jedisPoolConfig());
            jedisConnectionFactory.setTimeout(20000);
            jedisConnectionFactory.setPassword("");
            return jedisConnectionFactory;
        }else{
            JedisConnectionFactory jedisConnectionFactory=new JedisConnectionFactory();
            //读取本地配置
            jedisConnectionFactory.setHostName("192.168.0.23");
            jedisConnectionFactory.setPort(6379);
            jedisConnectionFactory.setTimeout(20000);
            jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
            return new JedisConnectionFactory();
        }
    }

    @Bean
    @DependsOn("jedisConnectionFactory")
    public RedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.setHashValueSerializer(new JdkSerializationRedisSerializer());
        return template;
    }

}